<template>
  <div />
</template>
<script lang="ts" setup>
import { localStorage } from '@/utils/local-storage';
import { SSO_TYPE } from '@/store/app';
import { useUserStore, RESET_CURRENT_USER } from '@/store/user';
import { koalLoginRequest } from '@/api/avic/system/SingleSignOnApi';
import { setExpireTime } from '@/utils/common-util';
const { proxy } = getCurrentInstance();
const redirectUrl = 'redirect_url';
const userStore = useUserStore();

onBeforeMount(() => {
  koalLogin();
});

async function koalLogin() {
  // 清除token
  userStore[RESET_CURRENT_USER]();
  // 记单点登录类型
  localStorage.set(SSO_TYPE, 'koalLogin');

  try {
    const response = await koalLoginRequest();
    const { code, data } = response;
    if (code === '200') {
      userStore.SET_TOKEN(data.token, data.refreshToken);
      setExpireTime(data.expireTime);

      // 重定向优先级 redirectUrl > 后台用户
      if (proxy.$route.fullPath.indexOf(redirectUrl) > -1) {
        window.name = 'portal';
        proxy.$router.push(decodeURIComponent(proxy.$route.fullPath.split(`${redirectUrl}=`)[1]));
      } else {
        // 单点登录成功后如果没有配置redirectUrl则需要根据用户类型判断是否跳转后台管理
        const loginUser = data.userInfo;
        const { consoleType } = loginUser;
        if (consoleType === '0' && proxy.$settings.consoleUrl) {
          let { consoleUrl } = proxy.$settings;
          consoleUrl = consoleUrl.endsWith('/') ? consoleUrl : `${consoleUrl}/`;
          window.name = 'console';
          window.open(`${consoleUrl}access-from-portal?access_token=${data.token}&redirect_url=/backstage`, 'console');
        } else {
          window.name = 'portal';
          proxy.$router.push('/');
        }
      }
    } else {
      proxy.$router.push({
        name: 'loginFail'
      });
    }
  } catch (error) {
    proxy.$router.push({
      name: 'loginFail'
    });
  }
}
</script>
